﻿using AutoMapper;
using BPMN.appilcation.IService;
using BPMN.Domain.ActionResult;
using BPMN.Domain.Entity;
using BPMN.Domid.Dto.PermissionDto;
using BPMN.Domid.Dto.RoleDto;
using BPMN.Domid.Dto.UserDtos;
using BPMN.Domid.IReposict;
using BPMN.Domid.Model.Users;
using BPMN.Domid.Share.AuditResult;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Linq;
using System.Resources;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using static BPMN.Domid.Dto.RoleDto.ListUserRoleDto;

namespace BPMN.appilcation.Service
{
    public class RoleUserService: IRoleUserService
    {
        private readonly IReposictBase<User> user;//用户
        private readonly IReposictBase<Role> role;//角色
        private readonly IReposictBase<Permission> permission;//权限
        private readonly IReposictBase<RolePermission> roleperission;//角色权限
        private readonly IReposictBase<UserRole> userrole;//用户角色
        private readonly IMapper mapper;

        public RoleUserService(IReposictBase<User> user,
            IReposictBase<Permission> permission,
            IReposictBase<RolePermission> roleperission,
            IReposictBase<UserRole> userrole,
            IMapper mapper,
            IReposictBase<Role> role)
        {
            this.user = user;
            this.role = role;
            this.permission = permission;
            this.roleperission = roleperission;
            this.userrole = userrole;
            this.mapper = mapper;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> GetLongin(UsersDto dto)
        {
            try
            {
                var result = (await user.GetAll()).Where(x => x.UserName == dto.UserName && x.Password == dto.Password).FirstOrDefault();
                if (result != null)
                {
                    return new ResultDto<string>
                    {
                        Code = ResultCode.Ok,
                        Message = "登录成功!",
                        Data = result.Id.ToString()
                    };
                }
                else
                {
                    return new ResultDto<string>
                    {
                        Code = ResultCode.Fail,
                        Message = "登录失败!",
                    };
                }
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 用户添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> UserAdd(CreateUpdateUserDto dto)
        {
            if((await user.GetAll()).Where(u=>u.UserName==dto.UserName).Count()>0)
            {
                return new ResultDto<string>()
                {
                    Code = ResultCode.Fail,
                    Message = "用户名已存在!",
                };
            }
            else
            {
                if(await user.Add(mapper.Map<User>(dto)) == 1){
                    return new ResultDto<string>()
                    {
                        Code = ResultCode.Ok,
                        Message = "操作成功!",
                    };
                }
                else
                {
                    return new ResultDto<string>()
                    {
                        Code = ResultCode.Fail,
                        Message = "添加失败!",
                    };
                }
                
            }
            
        }
        /// <summary>
        /// 用户修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> UserUpdate(CreateUpdateUserDto dto)
        {
                if (await user.Update(mapper.Map<User>(dto)) == 1)
                {
                    return new ResultDto<string>();
                }
                else
                {
                    return new ResultDto<string>(ResultCode.Fail,"操作失败");
                    
                }
        }
        /// <summary>
        /// 用户查询单条数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDto<UserresDto>> UserGet(int id)
        {
            try
            {
                var entity = await user.Get(id);
                return new ResultDto<UserresDto>()
                {
                    Code = ResultCode.Ok,
                    Message = "获取成功",
                    Data = mapper.Map<UserresDto>(entity)
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 用户查询全部数据
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<List<UserresDto>>> UserGetAll()
        {
            try
            {
                var entity = await user.GetAll();
                return new ResultDto<List<UserresDto>>()
                {
                    Code = ResultCode.Ok,
                    Message = "获取成功",
                    Data = mapper.Map<List<UserresDto>>(entity.ToList())
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 用户删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> UserDelete(int id)
        {
            try
            {
                if ((await user.Delete(id)==1))
                {
                    return new ResultDto<string>();
                }
                else
                {
                    return new ResultDto<string>(ResultCode.Fail, "操作失败");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> AddRoleDato(RoleDto dto)
        {
            try
            {
                if((await role.GetAll()).Where(r => r.RoleName == dto.RoleName).Count() > 0)
                {
                    return new ResultDto<string>
                    {
                        Code = ResultCode.Fail,
                        Message = "角色已存在!",
                    };
                }
                else
                {
                   if(await role.Add(mapper.Map<Role>(dto)) == 1)
                    {
                        return new ResultDto<string>
                        {
                            Code = ResultCode.Ok,
                            Message = "添加成功!",
                        };
                    }
                    else
                    {
                        return new ResultDto<string>
                        {
                            Code = ResultCode.Fail,
                            Message = "添加失败!",
                        };
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 角色修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> RoleUpdate(RoleDto dto)
        {
            if (await role.Update(mapper.Map<Role>(dto)) == 1)
            {
                return new ResultDto<string>();
            }
            else
            {
                return new ResultDto<string>(ResultCode.Fail, "操作失败");

            }
        }
        /// <summary>
        /// 用户查询单条数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDto<RoleDto>> RoleGet(int id)
        {
            try
            {
                var entity = await role.Get(id);
                return new ResultDto<RoleDto>()
                {
                    Code = ResultCode.Ok,
                    Message = "获取成功",
                    Data = mapper.Map<RoleDto>(entity)
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 查询角色信息
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<List<RoleDto>>> GetRoleDto()
        {
            try
            {
                var entity = await role.GetAll();
                return new ResultDto<List<RoleDto>>
                {
                    Code = ResultCode.Ok,
                    Message = "获取成功",
                    Data = mapper.Map<List<RoleDto>>(entity)
                };
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 查询角色信息
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<List<RoleDto>>> PageGetAllRoleDto(string? RoleName,int pageIndex,int pageSize,int totalCount,int pageCount)
        {
            try
            {
                var entity = await role.GetAll();
                if (!string.IsNullOrEmpty(RoleName))
                {
                    entity = entity.Where(x=>x.RoleName.Contains(RoleName));
                }
                 totalCount = entity.Count();
                 pageCount = (int)Math.Ceiling((totalCount * 1.0) / pageSize);
                
                return new ResultDto<List<RoleDto>>
                {
                    Code = ResultCode.Ok,
                    Message = "获取成功",
                    Data = mapper.Map<List<RoleDto>>(entity.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList())
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 角色删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> DeleteRoleDto(int id)
        {
            try
            {
                if((await role.Delete(id)) == 1)
                {
                    return new ResultDto<string>();
                }
                else
                {
                    return new ResultDto<string>(ResultCode.Fail, "操作失败!");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 用户注册信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> AddUserRole(AddUserRoleDto dto)
        {
            try
            {
                user.BeginTran();

                var entity = mapper.Map<User>(dto);
                await user.Add(entity);

                foreach (var item in dto.AddUserRoleDtosList)
                {
                    item.UserId = entity.Id;
                    await userrole.Add(mapper.Map<UserRole>(item));
                }
                user.CommitTran();

                return new ResultDto<string>();

            }
            catch (Exception)
            {
                user.RollbakTran();
                return new ResultDto<string>(ResultCode.Fail, "注册失败!");
                throw;
            }
        }
        /// <summary>
        ///显示
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<List<ListUserRoleDto>>> GetUserRole()
        {
            try
            {
                var userinfo = await user.GetAll();
                var roleinfo = await role.GetAll();
                var userroleinfo = await userrole.GetAll();

                var query = from a in userinfo
                            select new ListUserRoleDto
                            {
                                Id = a.Id,
                                UserAge = a.UserAge,
                                UserName = a.UserName,
                                RealName = a.RealName,
                                Email = a.Email,
                                Phone = a.Phone,

                                LisrUserRoleDtosList = (
                                from us in userinfo
                                join ur in userroleinfo on us.Id equals ur.UserId
                                join ro in roleinfo on ur.RoleId equals ro.Id
                                where a.Id == ur.UserId
                                select new ListUserRoleDtos
                                {
                                    UserId = us.Id,
                                    RoleId = ro.Id,
                                    RoleName = ro.RoleName
                                }).ToList()
                            };


                return new ResultDto<List<ListUserRoleDto>>
                {
                    Code = ResultCode.Ok,
                    Message = "操作成功",
                    Data = query.ToList(),
                };

            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        ///获取单条数据
        /// </summary>
        /// <returns></returns>
        public async Task<ResultDto<List<ListUserRoleDto>>> GetUserinfoRole(int id)
        {
            try
            {
                var userinfo = await user.GetAll();
                var roleinfo = await role.GetAll();
                var userroleinfo = await userrole.GetAll();

                var query = from a in userinfo
                            where a.Id == id
                            select new ListUserRoleDto
                            {
                                Id = a.Id,
                                UserAge = a.UserAge,
                                UserName = a.UserName,
                                RealName = a.RealName,
                                Email = a.Email,
                                Phone = a.Phone,

                                LisrUserRoleDtosList = (
                                from us in userinfo
                                join ur in userroleinfo on us.Id equals ur.UserId
                                join ro in roleinfo on ur.RoleId equals ro.Id
                                where a.Id == ur.UserId
                                select new ListUserRoleDtos
                                {
                                    UserId = us.Id,
                                    RoleId = ro.Id,
                                    RoleName = ro.RoleName
                                }).ToList()
                            };


                return new ResultDto<List<ListUserRoleDto>>
                {
                    Code = ResultCode.Ok,
                    Message = "操作成功",
                    Data = query.ToList(),
                };

            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 用户修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> UpdateRole(UpdateUserRoleDto dto)
        {
            try
            {
                user.BeginTran();

                var entity = await user.Get(dto.Id);

                entity.RealName= dto.RealName;
                entity.Email= dto.Email;
                entity.Phone= dto.Phone;
                entity.Phone = dto.Phone;

                await user.Update(entity);

                var userid = 0;

                foreach (var item in dto.UpdateUserRoleDtosList)
                {
                    userid = item.UserId;
                }

                var urdata = (await userrole.GetAll()).Where(x => x.UserId == userid).ToList();
                foreach (var item in urdata)
                {
                    await userrole.Delete(item.Id);
                }

                foreach (var item in dto.UpdateUserRoleDtosList)
                {
                    var urid = mapper.Map<UserRole>(item);
                    await userrole.Add(urid);
                }
                user.CommitTran();
                return new ResultDto<string> { };
                
            }
            catch (Exception)
            {
                user.RollbakTran();
                throw;
            }
        }

        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> AddPerDato(PermissionDtos dto)
        {
            try
            {
                if ((await permission.GetAll()).Where(p=>p.Name==dto.Name).Count() > 0)
                {
                    return new ResultDto<string>
                    {
                        Code = ResultCode.Fail,
                        Message = "权限名称已存在!",
                    };
                }
                else
                {
                    if (await permission.Add(mapper.Map<Permission>(dto)) == 1)
                    {
                        return new ResultDto<string>
                        {
                            Code = ResultCode.Ok,
                            Message = "添加成功!",
                        };
                    }
                    else
                    {
                        return new ResultDto<string>
                        {
                            Code = ResultCode.Fail,
                            Message = "添加失败!",
                        };
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 权限修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> PerUpdate(PermissionDtos dto)
        {
            if (await permission.Update(mapper.Map<Permission>(dto)) == 1)
            {
                return new ResultDto<string>();
            }
            else
            {
                return new ResultDto<string>(ResultCode.Fail, "操作失败");

            }
        }
        /// <summary>
        /// 根据角色查询权限信息
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetPerDto(int id)
        {
            try
            {
                var query = permission.GetAll().Result.Where(x => x.Pid == id).ToList();
                var list = from a in query
                           select new
                           {
                               value = a.Id,
                               label = a.Name,
                               children = GetPerDto(a.Id).Result
                           };
                return list.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 权限删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> DeletePerDto(int id)
        {
            try
            {
                if ((await permission.Delete(id)) == 1)
                {
                    return new ResultDto<string>();
                }
                else
                {
                    return new ResultDto<string>(ResultCode.Fail, "操作失败!");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> AddRolePer(RolePerDto dto)
        {
            try
            {
                var query = roleperission.GetAll().Result.Where(x => x.RoleId == dto.RoleId).ToList();
                if (query.Count() != 0)
                {
                    await roleperission.ResDel(query);
                }
                  List<RolePermission> rolePermissions = new List<RolePermission>();
                foreach (var item in dto.PermissionId.Split(','))
                {
                    rolePermissions.Add(new RolePermission { RoleId = dto.RoleId, PermissionId = int.Parse(item) });
                    
                }
                var roleper = await roleperission.AddRolu(rolePermissions);
                if (roleper > 0)
                {
                    return new ResultDto<string>();
                }
                else
                {
                    return new ResultDto<string>(ResultCode.Fail, "添加失败");
                }

            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 权限获取
        /// </summary>
        /// <param name="RoleId"></param>
        /// <returns></returns>
        public async Task<ResultDto<List<GetRoLEPermissionDto>>> GetRolePermissionsDto(int RoleId)
        {
            try
            {
                return new ResultDto<List<GetRoLEPermissionDto>>()
                {
                    Code = ResultCode.Ok,
                    Message = "获取成功!",
                    Data = mapper.Map<List<GetRoLEPermissionDto>>(roleperission.GetAll().Result.Where(x => x.RoleId == RoleId).ToList())
                };

            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 根据角色查询权限信息
        /// </summary>
        /// <returns></returns>
        private List<PerPtyeDtos> GetPerTerrDto(List<PermissionDtos> alist,int Pid)
        {
            try
            {
                var query = alist.Where(x => x.Pid == Pid).ToList();
                var list = from a in query
                           select new PerPtyeDtos
                           {
                               value = a.Id,
                               label = a.Name,
                               Url= a.Url,
                               children = GetPerTerrDto(alist,a.Id)
                           };
                return list.Count() == 0 ? null : list.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 菜单列显示
        /// </summary>
        /// <param name="Userid"></param>
        /// <returns></returns>
        public async Task<ResultDto<List<PerPtyeDtos>>> PerPermissionDtosShow(int Userid)
        {
            try
            {
                var users = (await userrole.GetAll()).ToList();
                var rolePermissions = (await roleperission.GetAll()).ToList();
                var permissions = (await permission.GetAll()).ToList();

                 var query = (from suserrole in users
                              join sroleper in rolePermissions
                              on suserrole.RoleId equals sroleper.RoleId
                              join spermission in permissions
                              on sroleper.PermissionId equals spermission.Id
                              where suserrole.UserId== Userid
                              select new PermissionDtos
                              {
                                  Id= spermission.Id,
                                  Name= spermission.Name,
                                  Url= spermission.Url,
                                  Pid= spermission.Pid,
                              }).Distinct().ToList();


                return new ResultDto<List<PerPtyeDtos>>
                {
                    Code = ResultCode.Ok,
                    Message = "获取成功!",
                    Data = GetPerTerrDto(query, 0)
                };
            }
            catch (Exception x)
            {

                return new ResultDto<List<PerPtyeDtos>>
                {
                    Code = ResultCode.Ok,
                    Message = "获取失败" + x.Message,
                };
            }
        }
    }
}
